<template>
  <split splitHeight="calc(100vh-5px)" leftWidth="240" style="margin-top: 4px; overflow: hidden">
    <template #paneL>
      <div class="searchFrame" style="padding-bottom: 2px">
        <span>筛选 </span>
        <a-input type="text" v-model:value="keyword" style="width: 192px; margin-left: 4px" @change="onSearch" autocomplete="off"/>
      </div>
      <PageWrapper :class="prefixCls" >
      <div :class="`${prefixCls}__content`" class="overflow-auto">
        <a-list>
          <template v-for="item in bankResult.records" :key="item.id">
            <a-list-item class="list" :class="selectBankIds.includes(item.id) ? 'active' : ''" @click="onSelect(item.id)">
              <a-list-item-meta>
                <template #avatar>
                  <svg class="icon svg-icon bank-icon" style="" v-if="item.logo">
                    <use :xlink:href="'#icon-' + item.logo"></use>
                  </svg>
                  <Image width="16px" src="../logo2.png" v-else></Image>
                </template>
                <template #title>
                  <span>{{ item.id + " " + item.djm }}</span>
                </template>
                <template #description>
                  <div>{{ item.lsye }} </div>
                </template>
              </a-list-item-meta>
            </a-list-item>
          </template>
        </a-list>
      </div>
      </PageWrapper>
      <div class="list-footer">合计：{{ bankResult.summary.lsye }}</div>
    </template>
    <template #paneR>
    <!-- 银行流水 -->
    <div class="jeecg-basic-table jeecg-basic-table-form-container">
      <a-form @keyup.enter.native="searchQuery">
        <a-row :gutter="8" type="flex">
          <a-col flex="135px">
            <a-form-item label="部门" :label-col="{ style: { width: '40px' } }" :wrapper-col="{ span: 18 }">
              <JDictSelectTag v-model:value="queryParam.ddlxIds" mode="multiple" :maxTagCount="0" dictCode="ddlxType@ddlxUser" placeholder="全部" :autofocus="false" @change="ddlxSelect" />
            </a-form-item>
          </a-col>

          <a-col flex="330px">
            <a-form-item label="记账日期" :label-col="{ style: { width: '70px' } }" >
              <!--a-month-picker v-model:value="pca.beginDate" :disabled-date="disabledStartDate" valueFormat="YYYY-MM" placeholder="" style="width: 90px" /> ~
              <a-month-picker v-model:value="pca.endDate" :disabled-date="disabledEndDate" valueFormat="YYYY-MM" placeholder="" style="width: 90px" /-->
              <a-date-picker v-model:value="queryParam.jzsjBegin" :disabled-date="disabledStartDate" valueFormat="YYYY-MM-DD" placeholder="" style="width: 115px" /> ~
              <a-date-picker v-model:value="queryParam.jzsjEnd" :disabled-date="disabledEndDate" valueFormat="YYYY-MM-DD" placeholder="" style="width: 115px" />
            </a-form-item>
          </a-col>

          <a-col flex="120px">
            <a-form-item label="状态" :label-col="{ style: { width: '40px' } }">
              <a-select name="stat" id="stat" v-model:value="queryParam.shbj" :disabled="shbjDisabled" class="w80" placeholder="全部" :showArrow="false" :allowClear="true" @change="shbjSelect">
                <a-select-option value="0">未审</a-select-option>
                <a-select-option value="1">已审</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col flex="125px">
            <a-form-item label="类型" :label-col="{ style: { width: '40px' } }" :wrapper-col="{ span: 17 }">
              <a-select v-model:value="queryParam.sflx" id="sflx" class="w80" placeholder="全部" :showArrow="false" :allowClear="true">
                <a-select-option value="1">收入</a-select-option>
                <a-select-option value="2">支出</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col flex="180px">
            <a-form-item label="备注" :label-col="{ style: { width: '50px' } }" :wrapper-col="{ span: 17 }">
              <a-input placeholder="" v-model:value.trim="queryParam.bz"></a-input>
            </a-form-item>
          </a-col>

          <a-col flex="auto" style="float: right; width: 100px">
            <span style="float: right; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="searchQuery" preIcon="ant-design:search">查询</a-button>
            </span>
          </a-col>
        </a-row>

        <a-row :gutter="8">
          <a-col flex="135px">
            <a-form-item label="划转" :label-col="{ style: { width: '40px' } }">
              <a-select v-model:value="queryParam.insider" id="insider" placeholder="全部" :showArrow="false" :allowClear="true" :disabled="insiderDisabled" @change="insiderSelect">
                <a-select-option value="0">不含</a-select-option>
                <a-select-option value="1">仅含</a-select-option>
              </a-select>
            </a-form-item>
          </a-col>

          <a-col flex="280px">
            <a-form-item label="金额" :label-col="{ style: { width: '70px' } }" >
              <a-input-number v-model:value.number="queryParam.beginJe" class="w-115px min-w-60px" /> ~ 
              <a-input-number v-model:value.number="queryParam.endJe" class="w-115px min-w-60px" />
            </a-form-item>
          </a-col>

          <a-col flex="230px">
            <a-form-item label="对方户名" :label-col="{ style: { width: '70px' } }" :wrapper-col="{ span: 17 }">
              <a-input placeholder="" v-model:value.trim="queryParam.dfhm"></a-input>
            </a-form-item>
          </a-col>

          <a-col flex="auto" style="float: right; width: 100px">
            <span style="float: right; overflow: hidden" class="table-page-search-submitButtons">
              <a-button type="primary" @click="caleQueryDate('1')" preIcon="ant-design:calendar-twotone">昨天</a-button>
              <a-button type="primary" @click="caleQueryDate('2')" preIcon="ant-design:field-number-outlined">本周</a-button>
              <a-button type="primary" @click="caleQueryDate('3')" preIcon="ant-design:insert-row-above-outlined">本月</a-button>
            </span>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <!-- table区域-begin -->
    <BasicTable @register="registerTable" :onRowClick="handleClick" :onRowDbClick="handleDblclick" :rowClassName="rowClassName" >
      <!--插槽:table标题-->
      <template #tableTitle>
        <a-button type="primary" preIcon="ant-design:plus-outlined" @click="handleCreate"> 新增 </a-button>
        <a-button type="primary" preIcon="ant-design:edit-outlined" @click="handleEdit" :disabled="editDisabled"> 编辑</a-button>
        <a-button type="primary" color="error" preIcon="ant-design:delete-twotone" @click="handleDelete" :disabled="deleDisabled" class="mr-4"> 删除 </a-button>
        <j-upload-button type="primary" color="success" preIcon="ant-design:arrow-up-outlined" @click="onImportXls">导入</j-upload-button>
        <a-button type="primary" color="warning" preIcon="ant-design:arrow-down-outlined" @click="onExportXls"> 导出 </a-button>
      </template>
      <template #srje="{ text, record }">
        <!--a-tooltip color="red" placement="right" v-if="record.uncouple == '1' && record.sflx == '1'">
          <template #title>分解 {{record.fjcn}} 笔，已分解：{{record.fjsr}}，未分解：{{record.wfjsr}}</template>
          <a-badge color="red" :count="25" dot><span class="text-red-500">{{ text }}</span></a-badge>
        </!--a-tooltip-->
        <a-popover placement="right" v-if="record.uncouple == '1' && record.sflx == '1'">
          <template #title>
            <span>已分解：{{record.fjsr}}，未分解：{{record.wfjsr}}</span>
          </template>
          <template #content>
            <div v-for="item in record.child" :key="item.id">
              {{ render.renderDict(item.ddlx, 'ddlxType').children + " - " + item.djm + " - " + item.srje}}
            </div>
          </template>
          <a-badge color="red" :count="25" dot><span class="text-red-500">{{ text }}</span></a-badge>
        </a-popover>
        <span class="text-red-500" v-else>{{ text }}</span>
      </template>
      <template #zcje="{ text, record }">
        <a-popover placement="right" v-if="record.uncouple == '1' && record.sflx == '2'">
          <template #title>
            <span>已分解：{{record.fjsr}}，未分解：{{record.wfjsr}}</span>
          </template>
          <template #content>
            <div v-for="item in record.child" :key="item.id">
              {{ render.renderDict(item.ddlx, 'ddlxType').children + " - " + item.djm + " - " + item.zcje}}
            </div>
          </template>
          <a-badge color="grenn" :count="25" dot><span class="text-grenn-500">{{ text }}</span></a-badge>
        </a-popover>
        <span class="text-grenn-500" v-else>{{ text }}</span>
      </template>
    </BasicTable>
    <!-- table区域-end-->
    </template>
  </split>

  <!-- 新增 -->
  <BankBusinessModal @register="registerBankBusinessAdd" @success="modalFormOk" :canResize="true"></BankBusinessModal>
</template>

<script lang="ts" setup name="bankBusiness-list">
  import { ref, computed, unref, reactive, toRaw, watch, watchEffect } from 'vue';
  import { BasicTable, TableAction, ActionItem, BasicColumn } from '/@/components/Table';
  import { Image } from 'ant-design-vue';
  import { useModal } from '/@/components/Modal';
  import { useListPage } from '/@/hooks/system/useListPage';
  import { render } from '/@/utils/common/renderUtils';
  import { bankBusinesslist, deleteBankRunning, getImportUrl, getExportUrl, bankList } from '/@/views/full/bank/types/bank.api';
  import { filterObj } from '/@/utils/common/compUtils';
  import { useMethods } from '/@/hooks/system/useMethods';
  import { BasicTree, TreeItem } from '/@/components/Tree';
  import { PageWrapper } from '/@/components/Page';

  import Icon from '/@/components/Icon/index';
  import Split from '/@/components/pt/split/Index.vue'
  import dayjs from 'dayjs';
  import JDictSelectTag from '/@/components/Form/src/jeecg/components/JDictSelectTag.vue';
  import BankBusinessModal from './modules/BankBusinessModal.vue';

  //----------定义变量 开始-------------------------------------------------------------
  const loading   = ref<boolean>(false);
  const prefixCls = 'list-basic';
  const insiderDisabled = ref<boolean>(false);
  const shbjDisabled = ref<boolean>(false);
  const editDisabled = ref<boolean>(true);
  const deleDisabled = ref<boolean>(true);

  //定义查询表单，查询条件
  const queryParam = reactive<any>({
    ddlxIds: [],
    today: '0', //未审
    jzsjBegin: dayjs().subtract( 3, 'month').startOf('month').format('YYYY-MM-DD'),
    jzsjEnd: dayjs().add(0, 'month').endOf('month').format('YYYY-MM-DD'),
    shbj: '',
    bankIds: [],
    sflx: null,
    insider: null,
    beginJe: '',
    endJe: '',
    orderId: '',
    dfhm: '',
  });

  //----------定义变量 结束-------------------------------------------------------------

  //----------银行列表 左边-----------------------------------------------------------
  //银行账号
  const activeIndex   = ref<Number>(0);
  const keyword       = ref<String>("");
  const allBankIds    = ref<any[]>([]);
  const selectBankIds = ref<any[]>([]);
  /**
   * 左则银行点击事件
   * @param key
   */
  function onSelect(key) {
    // 控制选中数组元素的进出
    let ids = unref(selectBankIds);
    if (ids.includes(key)) {
      ids = ids.filter(e => e !== key)
    } else {
      ids.push(key);
    }
    selectBankIds.value = [...ids];
    // 赋值查询参数
    if (ids.length > 0) {
      // 已选中
      key = ids.join(",");
      queryParam.bankIds = key;
    } else {
      // 未选中
      if (keyword.value && allBankIds.value.length > 0) {
        queryParam.bankIds = allBankIds.value;
      } else {
        queryParam.bankIds = [];
      }
    }
    //console.info("onSelect", selectBankIds.value, key, ids);
    searchQuery();
  }

  /**
   * 文本框值变化
   */
  const bankResult = reactive<any>({
    records: [],
    summary: {}
  });
  function onSearch() {
    let params = {};
    if (keyword.value) {
      params = { djm: keyword.value }
    }
    selectBankIds.value = []
    allBankIds.value    = []
    queryParam.bankIds  = []
    bankList(params).then(res => {
      bankResult.records  = res.records
      bankResult.summary = res.summary[0]
      if (res.records) {
        res.records.forEach(element => {
          allBankIds.value.push(element.id);
        });
        // 默认查询所有查询出来的银行id
        queryParam.bankIds = allBankIds.value.join(",");
      }
      // 如果筛选key不为空
      if (keyword.value) {
        searchQuery();
      }
    })
    console.info("onSearch", allBankIds.value);
  }

  onSearch();
  //----------银行列表 左边-----------------------------------------------------------


  //----------数据列表 右边-------------------------------------------------------------
  // 审核状态
  const statusFmt = ({ text }: { text: any }) => {
    if (text && text !== '合计') {
      const color = text == '0' ? 'green' : text == '1' ? 'red' : 'green';
      const value = text == '0' ? '未审' : text == '1' ? '已审' : '未审';
      return render.renderTag(value, color);
    }
  };

  // 部门翻译
  const ddlxFmt = ({ text, record }) => {
    if (record.uncouple == '1') {
      return '分解 '+ record.fjcn + "｜" + record.yshcn;
    } else if (record.orderId && record.orderId.indexOf('-9') > 0) {
      return '划转';
    } else {
      return render.renderDict(text, 'ddlxType')
    }
  };

  // 收付方式翻译
  const sffsFmt = ({ text, record }) => {
    const value = render.renderDict(text, 'sffsType');
    switch (text) {
      case '1':
        return render.renderColor(value, "green");
      case '3':
        return render.renderColor(value, "red");
      case '4':
        return render.renderColor(value, "purple");
      case '5':
        return render.renderColor(value, "blue");
      default:
        return text;
    }
  };

  // 数据列表 - 表头
  const columns: BasicColumn[] = [
    { title: '状态', align: 'center', dataIndex: 'shbj', width: 56, customRender: statusFmt },
    { title: '记账日期', align: 'center', dataIndex: 'jzsj', width: 80 },
    { title: '部门', align: 'center', dataIndex: 'ddlx', width: 70, customRender: ddlxFmt },
    { title: '银行账户', align: 'left', dataIndex: 'djm', width: 135 },
    { title: '对方户名', align: 'left', dataIndex: 'dfhm', width: 110 },
    { title: '方式', align: 'center', dataIndex: 'sffs', width: 45, customRender: sffsFmt },
    { title: '收入', align: 'right', dataIndex: 'srje', width: 85, className: 'text-red-500', slots: { customRender: 'srje' } },
    { title: '支出', align: 'right', dataIndex: 'zcje', width: 85, className: 'text-green-500', slots: { customRender: 'zcje' } },
    { title: '备注', align: 'left', dataIndex: 'bz', width: 110 },
    { title: '操作人', align: 'center', dataIndex: 'lrr', width: 60 },
    { title: '操作时间', align: 'center', dataIndex: 'lrsj', width: 110 },
  ];

  // 流水列表
  const { tableContext, onImportXls } = useListPage({
    designScope: 'bankbusiness-list',
    tableProps: {
      api: bankBusinesslist,
      columns: columns,
      size: 'small',
      showTableSetting: false,
      showIndexColumn: true, //行号
      showActionColumn: false,
      useSearchForm: false,
      resizeHeightOffset: 40,
      showSummary: true,
      summaryFunc: handleSummary,
      beforeFetch: (params) => Object.assign(params, filterObj(queryParam)),
    },
    importConfig: {
      url: getImportUrl,
      success: () => reload(),
    },
  });

  //注册table数据
  const [ registerTable, { reload, setProps, getRawDataSource, redoHeight }] = tableContext;
  //数据导出导入函数
  const { handleImportXls, handleExportXls } = useMethods();
  //----------数据列表 右边-----------------------------------------------------------

  //----------数据列表 事件-----------------------------------------------------------
  /* 日期控件 根据结束日期锁定最大可选日期 */
  function disabledStartDate(beginDate) {
    const endDate = queryParam.jzsjEnd;
    if (!beginDate || !endDate) {
      return false;
    }
    return beginDate.valueOf() > dayjs(endDate).valueOf();
  }

  /* 日期控件 根据开始日期锁定最小可选日期 */
  function disabledEndDate(endDate) {
    const beginDate = queryParam.jzsjBegin;
    if (!endDate || !beginDate) {
      return false;
    }
    return dayjs(beginDate).valueOf() > endDate.valueOf();
  }

  //部门下接框
  function ddlxSelect() {
    //有选择操作
    if (queryParam.ddlxIds && queryParam.ddlxIds.length > 0) {
      shbjDisabled.value = true;
      queryParam.shbj = '1';
      insiderDisabled.value = true;
      queryParam.insider = '0';
    } else {
      shbjDisabled.value = false;
      queryParam.shbj = '';
      insiderDisabled.value = false;
      queryParam.insider = '0';
    }
  }

  //是否包含划转流水数据：0 不含 1 仅含
  function insiderSelect() {
    if (queryParam.insider == '0') {
      shbjDisabled.value = false;
      queryParam.shbj = null;
    } else if (queryParam.insider == '1') {
      shbjDisabled.value = true;
      queryParam.shbj = null;
    } else {
      shbjDisabled.value = false;
      queryParam.shbj = null;
    }
  }

  //审核
  function shbjSelect() {
    // if ( queryParam.shbj == "0" ) {
    //   insiderDisabled.value = false;
    //   queryParam.insider = null;
    // } else if ( queryParam.shbj == "1" ) {
    //   insiderDisabled.value = true;
    //   queryParam.insider = "1";
    // } else {
    //   insiderDisabled.value = false;
    //   queryParam.insider = null;
    // }
  }

  function searchReset() {
    Object.assign(queryParam, { ddlxIds: [], ddzt: '', ywlx: '' });
    reload();
  }

  function searchQuery() {
    //filterObj
    let params = toRaw(filterObj(queryParam));
    if (typeof params.shbj === 'undefined') {
      params.shbj = '';
    }
    setProps({ searchInfo: params });
    reload();
  }

  function caleQueryDate(type) {
    if( type === '1') {
      //昨天
      queryParam.jzsjBegin = dayjs().subtract( 1, 'day').format('YYYY-MM-DD')
      queryParam.jzsjEnd = dayjs().subtract( 1, 'day').format('YYYY-MM-DD')
    } else if(type === '2') {
      //本周
      queryParam.jzsjBegin = dayjs().startOf('week').add(1, 'day').format('YYYY-MM-DD')
      queryParam.jzsjEnd = dayjs().startOf('week').add(7, 'day').format('YYYY-MM-DD')
    } else if(type === '3') {
      //本月
      queryParam.jzsjBegin = dayjs().startOf('month').format('YYYY-MM-DD')
      queryParam.jzsjEnd = dayjs().endOf('month').format('YYYY-MM-DD')
    } else if(type === '4') {
      //上月
      queryParam.jzsjBegin = dayjs().add(-1, 'month').startOf('month').format('YYYY-MM-DD')
      queryParam.jzsjEnd = dayjs().add(-1, 'month').endOf('month').format('YYYY-MM-DD')
    }
    searchQuery();
  }

  function handleSummary(tableData: Recordable[]) {
    const res = getRawDataSource();
    if (res) {
      return getRawDataSource().summary;
    } else {
      return [];
    }
  }
  //----------数据列表 事件-----------------------------------------------------------

  
  //----------新增流水 组件---------------------------------------------------------------
  // 新增流水
  const [registerBankBusinessAdd, { openModal: openBankBusiness }] = useModal();

  
  function handleDecompose() {

  }

  //单击行
  let selectRows = reactive<any>({ id: '', username: '' });
  function handleClick(record) {
    selectRows.id = record.id;
    selectRows.username = record.username;
    if (record.shbj == '1') {
      editDisabled.value = true;
      deleDisabled.value = true;
    } else {
      editDisabled.value = false;
      deleDisabled.value = false;
    }
  }

  //双击行
  function handleDblclick(record) {
    if (record.shbj === '0') {
      handleEdit();
    } else {
    }
  }

  function rowClassName(record, index) {
    return record.id === selectRows.id ? 'row-selected' : '';
  }

  function handleCreate() {
    openBankBusiness(true, { isUpdate: false });
  }

  function handleEdit() {
    let record = { id: selectRows.id };
    openBankBusiness(true, { isUpdate: true, record });
  }

  //新增编辑成功后，刷新列表
  function modalFormOk() {
    searchQuery();
  }

  /**
   * 删除事件
   */
  async function handleDelete() {
    let record = { id: selectRows.id };
    await deleteBankRunning(record, reload);
  }

  function onExportXls() {
    searchQuery();
    handleExportXls('银行流水', getExportUrl, filterObj(queryParam));
  }
  //----------业务事件---------------------------------------------------------------

  
</script>
<style lang="less" scoped>
  .list-basic {
    &__top {
      padding: 24px;
      text-align: center;
      background-color: @component-background;

      &-col {
        &:not(:last-child) {
          border-right: 1px dashed @border-color-base;
        }

        div {
          margin-bottom: 12px;
          font-size: 14px;
          line-height: 22px;
          color: @text-color;
        }

        p {
          margin: 0;
          font-size: 24px;
          line-height: 32px;
          color: @text-color;
        }
      }
    }

    &__content {
      padding: 0px;
      margin-top: 0px;
      background-color: @component-background;
      overflow: auto;
      cursor: pointer;

      .list {
        position: relative;
      }

      .list:hover {
        background: #FFFFF0;
      }

      .active {
        background: #FFFFCD;
      }

      .icon {
        font-size: 40px !important;
      }

      .extra {
        position: absolute;
        top: 20px;
        right: 15px;
        font-weight: normal;
        color: @primary-color;
        cursor: pointer;
      }

      .description {
        display: inline-block;
        width: 40%;
      }

      .info {
        display: inline-block;
        width: 30%;
        text-align: center;

        div {
          display: inline-block;
          padding: 0 20px;

          span {
            display: block;
          }
        }
      }

      .progress {
        display: inline-block;
        width: 15%;
        vertical-align: top;
      }
    }
  }

  .list-footer {
    border-top: 1px #eee solid;
    height: 30px;
    line-height: 30px;
    bottom: 0;
  }

  .table-page-search-submitButtons{
    button {
      margin-left: 5px;
    }
  }

  ::v-deep(.jeecg-page-wrapper) {
    height: calc(~'100vh - 170px') !important;
    overflow-y: auto;
  }

  ::v-deep(.jeecg-page-wrapper .jeecg-page-wrapper-content) {
    margin: 0px!important;
  }

  ::v-deep(.ant-list-item-meta-avatar) {
    margin-right: 0px;
  }

  ::v-deep(.ant-list-item) {
    padding: 5px 0 !important;
    color: rgba(0, 0, 0, 0.85);
    color: @primary-color;
  }

  ::v-deep(.bank-icon) {
    width: 17px;
    height: 17px;
    line-height: 17px;
    margin-right: 3px;
    margin-top: 3px;
    float: left;
  }

  ::v-deep(.ant-image) {
    float: left!important;
    margin-right: 5px;
    margin-top: 3px;
  }
</style>
